<template>
  <el-container>
    <el-aside :class="{ 'aside-menu': true }" v-show="showMenu">
      <div class="logo" @click="homeClick">
        <img src="../../assets/image/logo2.png" />
        <!-- <span v-show="!isCollapse">MF-BPM</span> -->
      </div>
      <el-menu router class="el-menu-vertical" :default-active="active" :collapse="isCollapse" style="height: 800px; overflow-y: auto;">
        <el-menu-item index="/workspace/forms" style="padding:0 3px!important;">
          <el-icon class="icon">
            <Plus />
          </el-icon>
          <template #title>
            <p class="title">{{$t('title.initiate')}}</p>
          </template>
        </el-menu-item>
        <el-menu-item index="/workspace/unfinished" style="padding:0 3px!important;">
          <el-icon class="icon">
            <Notification />
          </el-icon>
          <template #title>
            <p class="title">{{$t('title.backlog')}}</p>
          </template>
        </el-menu-item>
        <el-menu-item index="/workspace/finished" style="padding:0 3px!important;">
          <el-icon class="icon">
            <Finished />
          </el-icon>
          <template #title>
            <p class="title">{{$t('title.haveDone')}}</p>
          </template>
        </el-menu-item>
        <el-menu-item index="/workspace/submit" style="padding:0 3px!important;">
          <el-icon class="icon">
            <Position />
          </el-icon>
          <template #title>
            <p class="title">{{$t('title.sent')}}</p>
          </template>
        </el-menu-item>
        <el-menu-item index="/workspace/cc" style="padding:0 3px!important;">
          <el-icon class="icon">
            <CopyDocument />
          </el-icon>
          <template #title>
            <p class="title">{{$t('title.copy')}}</p>
          </template>
        </el-menu-item>
        <el-menu-item index="/workspace/report" v-if='menus.length>0 || roles.includes("WFLOW_APPROVAL_ADMIN")' style="padding:0 3px!important;">
          <el-icon class="icon">
            <Management />
          </el-icon>
          <template #title>
            <p class="title">{{$t('title.reportCenter')}}</p>
          </template>
        </el-menu-item>
        <template v-if='!isMobile && roles.includes("WFLOW_APPROVAL_ADMIN")' style="padding:0 3px!important;">
          <el-divider></el-divider>
          <el-menu-item index="/workspace/instances">
            <el-icon class="icon">
              <PieChart />
            </el-icon>
            <template #title>
              <p class="title">{{$t('title.management')}}
              </p>
            </template>
          </el-menu-item>
          <el-menu-item index="/workspace/formsPanel" style="padding:0 3px!important;">
            <el-icon class="icon">
              <Tools />
            </el-icon>
            <template #title>
              <p class="title">{{$t('title.procseeMang')}}
              </p>
            </template>
          </el-menu-item>
          <el-menu-item index="/workspace/subProcess" style="padding:0 3px!important;">
            <el-icon class="icon">
              <Coin />
            </el-icon>
            <template #title>
              <p class="title">{{$t('title.subprocess')}}
              </p>
            </template>
          </el-menu-item>
          <el-menu-item index="/workspace/roleManage" style="padding:0 3px!important;">
            <el-icon class="icon">
              <FirstAidKit />
            </el-icon>
            <template #title>
              <p class="title">{{$t('title.roleMang')}}
              </p>
            </template>
          </el-menu-item>
          <el-menu-item index="/workspace/deptAllocation" style="padding:0 3px!important;">
            <el-icon class="icon">
              <Money />
            </el-icon>
            <template #title>
              <p class="title">{{$t('title.allocation')}}</p>
            </template>
          </el-menu-item>
          <el-menu-item index="/workspace/dictionaryConfiguration" style="padding:0 3px!important;">
            <el-icon class="icon">
              <List />
            </el-icon>
            <template #title>
              <p class="title">{{$t('title.configuration')}}</p>
            </template>
          </el-menu-item>
          <el-menu-item index="/workspace/errorInfo" style="padding:0 3px!important;">
              <el-icon class="icon">
                <Refresh />
              </el-icon>
              <template #title>
                <p class="title">{{$t('title.interface')}}</p>
              </template>
          </el-menu-item>
        </template>
      </el-menu>
    </el-aside>
    <el-container class="container">
      <el-header height="80px">
        <div class="action" v-if="false">
          <el-icon @click="isCollapse = !isCollapse">
            <ArrowRight v-if="isCollapse" />
            <ArrowLeft v-else />
          </el-icon>
        </div>
        <div class="message" v-show="!showMenu || !isMobile">
          <el-popover placement="bottom-end" width="300" trigger="click">
            <div class="notify">
              <el-empty :image-size="50" :description="$t('webAuto.NoNews')" v-if="notify.total === 0"></el-empty>
              <div v-for="msg in notify.records" :key="msg.id" class="notify-item">
                <el-row>
                  <el-col :span="2">
                    <div class="notify-item-type-icon">
                      <el-icon v-if="msg.type === 'SUCCESS'" color="#02b068">
                        <SuccessFilled />
                      </el-icon>
                      <el-icon v-else-if="msg.type === 'WARNING'" color="#f78f5f">
                        <WarningFilled />
                      </el-icon>
                      <el-icon v-else-if="msg.type === 'ERROR'" color="#f25643">
                        <CircleCloseFilled />
                      </el-icon>
                      <el-icon v-else color="#8c8c8c">
                        <InfoFilled />
                      </el-icon>
                    </div>
                  </el-col>
                  <el-col :span="22">
                    <div class="notify-item-title" @click="toNotify(msg)">{{ msg.title }}</div>
                    <ellipsis hoverTip class="notify-item-content" :content="msg.content" />
                  </el-col>
                </el-row>
                <span class="notify-item-time">{{ msg.createTime.substring(5, 16) }}</span>
                <el-button type="primary" link class="notify-btn" @click="readNotify(msg.id)">{{$t('webAuto.READ')}}</el-button>
              </div>
            </div>
            <div class="notify-action" v-show="notify.total > 0">
              <el-button type="primary" link @click="--params.pageNo" :disabled="params.pageNo <= 1">{{$t('webAuto.previousPage')}}</el-button>
              <el-button type="primary" link @click="readNotify(null)">{{$t('webAuto.hasRead')}}</el-button>
              <el-button type="primary" link @click="++params.pageNo"
                :disabled="notify.total <= params.pageSize * notify.current">{{$t('webAuto.nextPage')}}
              </el-button>
            </div>
            <template #reference>
              <el-badge :hidden="notify.total === 0" :value="notify.total">
                <el-icon>
                  <Bell />
                </el-icon>
              </el-badge>
            </template>
          </el-popover>
        </div>
        <!-- 多语言 -->
        <div class="language" @click="changeLanguage(langIndex+1)">
          <img class="langs" src="../../assets/language/lang.png" />
          <span>{{ langIndex == 0 ? 'CN' : langIndex == 1 ? 'EN' : 'ES' }}</span>
        </div>
        <el-dropdown class="user-avatar">
          <w-avatar :src="user.avatar" :name="user.name"></w-avatar>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="switchUser">
                <el-icon>
                  <Sort />
                </el-icon>
                {{$t('webAuto.SwitchAccounts')}}
              </el-dropdown-item>
              <el-dropdown-item @click="showUserCenter">
                <el-icon>
                  <User />
                </el-icon>
                {{$t('webAuto.PersonalCenter')}}
              </el-dropdown-item>
              <el-dropdown-item @click="showCenter">
                <el-icon>
                  <Close />
                </el-icon>
                {{$t('webAuto.ChangePassword')}}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
    <el-dialog :size="isMobile ? '100%' : '500px'" direction="rtl" :title="$t('webAuto.ApprovalDetails')" closeFree width="1400px"
      style="margin:20px auto 0" :close-on-click-modal="false" :close-on-press-escape="false" v-model="processVisible">
      <instance-preview v-if="processVisible" :instance-id="selectInstance" @handler-after="processVisible = false" />
    </el-dialog>
    <org-picker :title="$t('webAuto.userToSwitch')" :pc-mode="!isMobile" type="user" ref="orgPicker" :selected="nowSelected"
      @ok="selected" />
    <w-dialog :title="$t('webAuto.PersonalCenter')" v-model="userCenterVisible" @ok="userCenterOk">
      <el-tabs defaultActive="userInfo" v-if="userCenterVisible" v-model="activeTab" tab-position="left"
        style="height: 220px">
        <el-tab-pane name="userInfo" :label="$t('webAuto.Information')">
          <user-info />
        </el-tab-pane>
        <el-tab-pane name="approvalAgent" :label="$t('webAuto.ApprovalAgency')">
          <approval-agent ref="agent" />
        </el-tab-pane>
        <el-tab-pane name="other" :label="$t('webAuto.OtherSettings')">{{$t('webAuto.None')}}</el-tab-pane>
      </el-tabs>
    </w-dialog>
    <w-dialog :title="$t('webAuto.ChangePassword')" v-model="changePassWord" width="500px" @ok="passWordClick" destroy-on-close>
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon label-width="auto"
        class="demo-ruleForm">
        <el-form-item :label="$t('webAuto.OriginalPassword')" :rules="[{ required: true, message: $t('webAuto.OriginalPasswordRequired') }]">
          <el-input v-model="ruleForm.pass" autocomplete="off" :placeholder="$t('webAuto.PleaseInputPassword')"
            :type="addPassFlag ? 'text' : 'password'">
            <template #suffix>
              <span @click="addPassFlag = !addPassFlag">
                <el-icon v-if="addPassFlag">
                  <View />
                </el-icon>
                <el-icon v-else>
                  <Hide />
                </el-icon>
              </span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('webAuto.NewPassword')" :rules="[{ required: true, message: $t('webAuto.newPasswordRequired') }]">
          <el-input v-model="ruleForm.newPass" autocomplete="off" :placeholder="$t('webAuto.enterNewPassword')"
            :type="addPassFlag2 ? 'text' : 'password'">
            <template #suffix>
              <span @click="addPassFlag2 = !addPassFlag2">
                <el-icon v-if="addPassFlag2">
                  <View />
                </el-icon>
                <el-icon v-else>
                  <Hide />
                </el-icon>
              </span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('webAuto.RepeatPassword')" :rules="[{ required: true, message: $t('webAuto.DuplicateRequired') }]">
          <el-input v-model="ruleForm.checkPass" autocomplete="off" :placeholder="$t('webAuto.enterNewPassword')"
            :type="addPassFlag3 ? 'text' : 'password'">
            <template #suffix>
              <span @click="addPassFlag3 = !addPassFlag3">
                <el-icon v-if="addPassFlag3">
                  <View />
                </el-icon>
                <el-icon v-else>
                  <Hide />
                </el-icon>
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </w-dialog>
  </el-container>
</template>

<script>
import { login, updatePassword } from '@/api/sys'
import UserInfo from './my/UserInfo.vue'
import ApprovalAgent from './my/ApprovalAgent.vue'
import { getUserNotify, readNotify } from '@/api/notify'
import OrgPicker from '../../components/common/OrgPicker.vue'
import InstancePreview from './approval/ProcessInstancePreview2.vue'
import { errorMessages } from '@vue/compiler-sfc'
import { View, Hide } from '@element-plus/icons-vue';
import { getLang } from '@/i18n/index'

export default {
  name: 'workSpace',
  components: { OrgPicker, InstancePreview, UserInfo, ApprovalAgent },
  data() {
    return {
      isCollapse: false,
      timer: null,
      params: {
        pageSize: 5,
        pageNo: 1,
      },
      notify: {
        records: [],
      },
      activeTab: 'userInfo',
      selectInstance: null,
      processVisible: false,
      userCenterVisible: false,
      changePassWord: false,
      ruleForm: {
        pass: '',
        newPass: '',
        checkPass: '',
      },
      ruleFormRef: '',
      passFlag: false,
      addPassFlag: false,
      passFlag2: false,
      addPassFlag2: false,
      passFlag3: false,
      addPassFlag3: false,
      roles: localStorage.getItem('roles') || '', // 角色判断显示权限
      langTypes: ["中文", "English", "español"],
      langIndex: 0,
      menus:(localStorage.getItem('menus')||'')
    }
  },
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  mounted() {
    // console.log(localStorage.getItem('lang'),this.langTypes.indexOf(localStorage.getItem('lang')))
    let index = this.langTypes.indexOf(localStorage.getItem('lang'))
    if (index != -1) {
      this.langIndex = index
    }
    if (this.isMobile) {
      this.isCollapse = true
    }
    let a = JSON.parse(localStorage.getItem('loginUser')) || {}
    this.user.name = a?.name
    this.user.avatar = a?.avatar
    this.getUserNotify()
    this.timerGetNotify(20)
    // if (!a || !a?.id) {
    //   this.$alert(
    //     '无法识别您的身份，请点击右上角头像选择当前体验人员',
    //     {
    //       confirmButtonText: '',
    //       callback: (action) => {
    //         this.switchUser()
    //       },
    //     }
    //   )
    // } else {
    //   this.getUserNotify()
    //   this.timerGetNotify(5)
    // }
  },
  computed: {
    loginUser() {
      return this.$store.state.loginUser
    },
    isMobile() {
      return window.screen.width < 450
    },
    showMenu() {
      if (this.isMobile) {
        this.roles = localStorage.getItem('roles')
        console.log(this.roles)
        return !this.isCollapse
      }
      return true
    },
    user() {
      return this.$store.state.loginUser
    },
    nowSelected() {
      if (this.user.id) {
        return [this.user]
      } else {
        return []
      }
    },
    active() {
      if (this.$route.path === '/workspace') {
        return this.$router.push('/workspace/forms')
      }
      return this.$route.path
    },
  },
  methods: {
    // 多语言切换
    changeLanguage(index) {
      console.log(index)
      this.langIndex+=1
      if ( this.langIndex > 2) {
        this.langIndex = 0
        let type = this.langTypes[this.langIndex];
        getLang(type)
      }else{
        let type = this.langTypes[index];
        getLang(type)
      }
    },
    homeClick(){
      this.$router.push('/')
    },
    getUserNotify() {
      getUserNotify(this.params).then((res) => {
        this.notify = res.data
      }).catch((err) => {
        if (this.timer) {
          clearInterval(this.timer)
        }
        this.$err(err, this.$t('webAuto.FailedMessage'))
        this.$router.push('/login')
      })
    },
    userCenterOk() {
      if (this.activeTab === 'approvalAgent') {
        this.$confirm(
          this.$t('webAuto.AllApprovalSettings'),
          this.$t('webAuto.prompt'),
          {
            confirmButtonText: this.$t('webAuto.sure'),
            cancelButtonText: this.$t('webAuto.cancel'),
            type: 'warning',
          }
        ).then(() => {
          this.$refs.agent.setUserAgent(() => {
            this.userCenterVisible = false
          })
        })
      }
    },
    passWordClick() {
      console.log(this.ruleForm)
      if (this.ruleForm.pass == '' || this.ruleForm.newPass == '' || this.ruleForm.checkPass == '') return this.$ok(errorMessages, this.$t('webAuto.informationCorrectly'))
      if (this.ruleForm.newPass != this.ruleForm.checkPass) return this.$ok(errorMessages, this.$t('webAuto.passwordTwice'))
      updatePassword({
        oldPassword: this.ruleForm.pass,
        newPassword: this.ruleForm.newPass
      }).then(res => {
        this.$ok(res, this.$t('webAuto.changeSuccess'))
        this.changePassWord = false
      }).catch((err) => {
        this.$err(err, this.$t('webAuto.originalPasswordIncorrect'))
      })
    },
    showUserCenter() {
      this.userCenterVisible = true
    },
    showCenter() {
      this.changePassWord = true
    },
    switchUser() {
      // this.$refs.orgPicker.show()
      this.$router.push({ name: 'login' });
    },
    toNotify(msg) {
      if (this.$isNotEmpty(msg.instanceId)) {
        this.selectInstance = msg.instanceId
        this.processVisible = true
      }
    },
    readNotify(id) {
      let list = id ? [id] : this.notify.records.map((n) => n.id)
      readNotify(list)
        .then((rsp) => {
          this.$ok(rsp, this.$t('webAuto.ReadSuccessfully'))
          this.getUserNotify()
        })
        .catch((err) => {
          this.$err(err, this.$t('webAuto.ReadFailed'))
        })
    },
    timerGetNotify(cycle) {
      if (this.timer) {
        clearInterval(this.timer)
      }
      this.timer = setInterval(() => this.getUserNotify(), cycle * 6000)
    },
    selected(user) {
      if (user.length > 0) {
        login(user[0].id)
          .then((rsp) => {
            let user = {
              id: rsp.data.userId,
              name: rsp.data.userName,
              avatar: rsp.data.avatar,
              position: rsp.data.position,
              type: 'user',
            }
            this.roles = rsp.data.roles
            localStorage.setItem('roles', JSON.stringify(this.roles))
            this.$store.state.loginUser = user
            localStorage.setItem('loginUser', JSON.stringify(user))
            localStorage.setItem('wflow-token', rsp.data.token)
            window.navigation.reload()
          })
          .catch((e) => {
            this.$err(err, this.$t('webAuto.LoginFailed'))
          })
      }
    },
  },
  watch: {
    params: {
      deep: true,
      handler() {
        this.getUserNotify()
      },
    },
  },
}
</script>

<style lang="less" scoped>
@header-height: 80px;

.notify {
  max-height: 200px;
  background: @theme-aside-bgc;
  overflow-y: auto;

  .notify-item:last-child {
    border-bottom: 2px solid @theme-aside-bgc;
  }

  .notify-item {
    border-top: 2px solid @theme-aside-bgc;
    padding: 5px;
    background: white;
    position: relative;
    border-radius: 5px;

    .notify-item-title {
      cursor: pointer;
      color: #3b3b3b;

      &:hover {
        color: @theme-primary;
      }
    }

    .notify-item-content {
      color: #8c8c8c;
      padding: 5px 0;
      font-size: smaller;
    }

    .notify-item-time {
      position: absolute;
      right: 45px;
      top: 7px;
      font-size: 12px;
      color: #8c8c8c;
    }

    .notify-btn {
      position: absolute;
      right: 5px;
      top: 8px;
    }

    .notify-item-type-icon {
      font-size: 18px;
    }
  }
}

.notify-action {
  display: flex;
  padding-top: 5px;
  justify-content: space-between;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: auto;
  //min-height: 400px;
  min-width:65px;
}

.m-aside-menu {
  position: fixed;
  z-index: 999;
  height: 100vh;
}

:deep(.el-menu-item) .icon {
  color: #909399;
}

:deep(.el-menu-item.is-active) .icon {
  color: @theme-primary;
}


.aside-menu {
  background: @theme-aside-bgc;
  // background-color: #D64445;
  width: auto !important;

  :deep(.icon) {
    font-size: large;
    margin-right: 5px;
  }

  .logo {
    height: @header-height;
    line-height: @header-height;
    display: flex;
    align-items: center;
    margin-left: 10px;

    img {
      width: 45px;
      height: 30px;
      margin-right: 10px;
      padding: 5px;
      border-radius: 12px;
    }

    span {
      font-size: 14px;
      font-weight: bold;
      color: black;
    }
  }

  &::-webkit-scrollbar {
    width: 0;
    height: 0;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 16px;
  }
}

:deep(.el-menu) {
  margin: 0 0 10px 0;
  background: @theme-aside-bgc;
  // background-color: #D64445;
  overflow: hidden;
  box-sizing: border-box;

  .el-menu-item {
    height: 60px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    overflow: hidden;
    margin: 4px 0;
    // border-radius: 7px;
  }

  .icon {
    font-size: 40px;
    // color: #fff;
  }

  .title {
    height: 30px;
    margin: 0 !important;
    line-height: 10px;
    font-size: 14px;
    // color: #fff;
  }

  .el-divider--horizontal {
    margin: 12px 0;
  }

  .el-menu-item.is-active {
    background: #e6f1fc;
    // background-color: #eba2a2;
  }
}

:deep(.el-badge) {
  line-height: normal;
}

:deep(.container) {
  background: white;
  height: 100vh;

  .el-header {
    position: relative;
    line-height: @header-height;
    // border-bottom: 1px solid #eeeeee;

    .action {
      position: absolute;
      height: @header-height;
      line-height: @header-height;

      :deep(.icon) {
        cursor: pointer;
        padding: 5px;
      }
    }
  }

  .user-avatar {
    cursor: pointer;
    position: absolute;
    right: 30px;
    height: 60px;
  }

  .message {
    position: absolute;
    right: 170px;
    margin: -10px auto;

    .icon {
      font-size: 18px;
      color: #a2a4a8;
      padding: 1px;
      cursor: pointer;

      &:hover {
        color: #6d6e70;
      }
    }
  }
}

@media screen and (max-width: 800px) {
  :deep(.el-main) {
    padding: 10px;

    .group {
      margin: 0 0 15px 0px !important;
    }
  }
}

::-webkit-scrollbar {
  width: 4px;
  height: 4px;
  background-color: white;
}

::-webkit-scrollbar-thumb {
  border-radius: 16px;
  background-color: #e8e8e8;
}

.language {
  height: 100%;
  width: 35px;
  margin: 0 3px;
  position: absolute;
  top: 0;
  right: 120px;
  display: flex;
  flex-direction: row;

  .langs {
    height: 15px;
    width: 15px;
    margin: 22px auto;
  }

  span {
    display: inline-block;
    font-size: 13px;
    margin-top: -10px;
  }
}

.language::after {
  content: '';
  width: 2px;
  height: 15px;
  position: absolute;
  left: -6px;
  top: 22px;
  background-color: rgb(0, 123, 255);
}
</style>
